//
//  NSFileManager+File.m
//  qwerqe
//
//  Created by ejiang on 15/1/16.
//  Copyright (c) 2015年 ejiang. All rights reserved.
//

#import "NSFileManager+File.h"

@implementation NSFileManager (File)  
/*!
 * @brief 判断文件是否存在于沙盒中
 * @param fileName 文件路径名
 * @return 返回YES表示存在，返回NO表示不存在
 */
- (BOOL)isFileExists:(NSString *)filePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    
    return result;
}

/*!
 * @brief 判断文件是否超时
 * @param filePath 文件路径名
 * @param timeout 限制的超时时间，单位为秒
 * @return 返回YES表示超时，返回NO表示未超时
 */
- (BOOL)isFile:(NSString *)filePath timeout:(NSTimeInterval)timeout {
    if ([[NSFileManager defaultManager] isFileExists:filePath]) {
        NSError *error = nil;
        NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath
                                                                                    error:&error];
        if (error) {
            return YES;
        }
        if ([attributes isKindOfClass:[NSDictionary class]] && attributes) {
            //  NSLog(@"%@", attributes);
            NSString *createDate = [attributes objectForKey:@"NSFileModificationDate"];
            createDate = [NSString stringWithFormat:@"%@", createDate];
            if (createDate.length >= 19) {
                createDate = [createDate substringToIndex:19];
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                
                NSDate *sinceDate = [formatter dateFromString:createDate];
                NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:sinceDate];
                return interval <= 0;
            }
        }
    }
    return YES;
}


/**
 * 返回解压成功或失败.需要使用到ZipArchive
 * srcfile:待解压文件全路径 destfile：解压文件全路径.
 **/

//+(BOOL)UnZipFile:(NSString*)srcFile ToFile:(NSString *)destFile withdeleteflag:(BOOL) bDel
//{
//    BOOL bUnZip = false;
//    ZipArchive *zip = [[ZipArchive alloc] init];
//    
//    NSString *sZipPath = srcFile;
//    
//    NSString *unZipTo = destFile;
//    
//    if ([zip UnzipOpenFile:sZipPath])
//        
//    {
//        
//        [zip UnzipFileTo:unZipTo overWrite:YES];
//        
//        [zip UnzipCloseFile];
//        bUnZip=YES;
//        
//    }
//    [zip release];
//    
//    if (bDel) {
//        [self deleteFile:sZipPath];
//    }
//    
//    
//    return bUnZip;
//}

/**
 * 判断文件夹是否存在，不存在则创建对应文件夹.
 * strDir:文件夹全路径.
 **/


+(void)IfNotCreateDir:(NSString*)strDir
{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:strDir  isDirectory:&isDir];
    
    if(!(isDirExist && isDir))
    {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:strDir withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir){
            NSLog(@"Create  Directory Failed.");
        }
        NSLog(@"%@",strDir);
    }
    
}

/**
 *  删除文件.
 * strDir:文件全路径.
 **/
+(void)deleteFile:(NSString*)strDir
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager removeItemAtPath:strDir error:nil]) {
        NSLog(@"remove file error.");
    }
    else
    {
        NSLog(@"remove file success.");
    }
    
}

/**
 *  复制文件.
 * srcFile:原文件全路径.destFile：目标文件全路径
 **/
+(BOOL)CopyFile:(NSString *)srcFile ToFile:(NSString *)destFile
{
    NSError *error=nil;
    BOOL success = [[NSFileManager defaultManager] copyItemAtPath:srcFile toPath:destFile error:&error];
    
    if (!success){
        NSAssert1(0,@"Failed to copy file '%@'.", [error localizedDescription]);
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}

/**
 * 判断文件是否存在，不存在则创建.
 * strFile:文件全路径.
 **/

+(BOOL)CreateFileIfNotExist:(NSString *)strFile
{
    //创建文件管理器
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //查找文件，如果不存在，就创建一个文件
    
    if (![fileManager fileExistsAtPath:strFile]) {
        
        return  [fileManager createFileAtPath:strFile contents:nil attributes:nil];
        
    }
    return true;
}

/**
 * 读取文本文件的每行，写入nsarray.
 * strFile:文件全路径.
 **/

+(NSArray*)readTxtLines:(NSString *)strFile
{
    NSArray *lines;/*将文件转化为一行一行的*/
    NSLog(@"content:%@",[NSString stringWithContentsOfFile:strFile encoding:NSUTF8StringEncoding error:nil]);
    lines = [[NSString stringWithContentsOfFile:strFile encoding:NSUTF8StringEncoding error:nil]componentsSeparatedByString:@"\n"];
    return lines;
}

/**
 * 读取文本文件的每行中制定字符类间的数据.
 * strFile:文件全路径.strPreFlag：前分割字符，如“<";strBackFlag:前分割字符，如“>";
 **/

+(NSArray*)readTxtLines:(NSString *)strFile withPreFlag:(NSString *)strPreFlag AndBackFlag:(NSString *)strBackFlag
{
    NSString *tmp;
    NSArray *lines;/*将文件转化为一行一行的*/
    lines = [[NSString stringWithContentsOfFile:strFile encoding:NSUTF8StringEncoding error:nil]componentsSeparatedByString:@"\n"];

    NSEnumerator *nse = [lines objectEnumerator];
    
    // 读取如<>里的内容
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    while(tmp = [nse nextObject]) {
        if (tmp !=nil || ![tmp isEqualToString:@""]) {
            NSString *stringBetweenBrackets = nil;
            NSScanner *scanner = [NSScanner scannerWithString:tmp];
            [scanner scanUpToString:strPreFlag intoString:nil];
            [scanner scanString:strPreFlag intoString:nil];
            [scanner scanUpToString:strBackFlag intoString:&stringBetweenBrackets];
            if (stringBetweenBrackets !=nil) {
                [arr addObject:stringBetweenBrackets];
            }
            
            
        }
    }
    return arr;
}

/**
 * 判断文件是否可读.
 * strFile:文件全路径;
 **/
+(BOOL)IsFileCanRead:(NSString *)strFile
{
    return [[NSFileManager defaultManager] isReadableFileAtPath:strFile];
}

/**
 * 判断文件是否可写.
 * strFile:文件全路径;
 **/

+(BOOL)IsFileCanWrite:(NSString *)strFile
{
    return [[NSFileManager defaultManager] isWritableFileAtPath:strFile];
}

/**
 * 判断文件是否相同.
 *
 **/

+(BOOL)IsFile:(NSString *)strSrcFILE equaltofile:(NSString *)strDestFile
{
    return [[NSFileManager defaultManager] contentsEqualAtPath:strSrcFILE andPath:strDestFile];
}

/**
 * 修改文件名.
 *
 **/

+(BOOL)reNameFile:(NSString *)strOldFile toFile:(NSString *)strNewFile
{
    //将文件 newfile.txt重命名为 newfile2.txt
    return [[NSFileManager defaultManager] moveItemAtPath:strOldFile toPath:strNewFile error:nil];
}
@end
